<?php
namespace Admin\Models\device;

use Admin\Models\BaseModel;
use Admin\Models\ims\XHImsApplyTablet;
use Admin\Models\user\XhsysUser;
use Helpers\User;
use Phalcon\Di;

class XhsysUsertablet extends BaseModel
{

    /**
     *
     * @var integer
     * @Primary
     * @Identity
     * @Column(type="integer", length=20, nullable=false)
     */
    public $iUTId;

    /**
     *
     * @var integer
     * @Column(type="integer", length=11, nullable=true)
     */
    public $iStaffId;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $sReceiverName;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $sReceiverAccount;

    /**
     *
     * @var string
     * @Column(type="string", length=20, nullable=true)
     */
    public $sReceiverPhone;

    /**
     *
     * @var integer
     * @Column(type="integer", length=2, nullable=true)
     */
    public $iReceivePurpose;

    /**
     *
     * @var string
     * @Column(type="string", nullable=true)
     */
    public $tReceiveTime;

    /**
     *
     * @var string
     * @Column(type="string", length=255, nullable=true)
     */
    public $sDevNumber;

    /**
     *
     * @var string
     * @Column(type="string", length=255, nullable=true)
     */
    public $sDevType;

    /**
     *
     * @var string
     * @Column(type="string", length=255, nullable=true)
     */
    public $sIMei;

    /**
     *
     * @var string
     * @Column(type="string", length=255, nullable=true)
     */
    public $sMacAddress;

    /**
     * @var integer
     * @Column(type="integer", length=20, nullable=true)
     */
    public $iNowReceiverId;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $sNowReceiverName;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $sNowReceiverAccount;

    /**
     *
     * @var string
     * @Column(type="string", nullable=true)
     */
    public $tNowReceiveTime;

    /**
     *
     * @var integer
     * @Column(type="integer", nullable=true)
     */
    public $iSchoolId;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $sRealUserName;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $sRealUserAccount;

    /**
     * @var
     * @Column(type="string", length=255, nullable=true)
     */
    public $sRemark;

    /**
     *
     * @var integer
     * @Column(type="integer", length=4, nullable=true)
     */
    public $bDone;

    /**
     *
     * @var integer
     * @Column(type="integer", length=4, nullable=true)
     * 1=待领用，2=已领用，3=已归还
     */
    public $iReceiveStatus;

    /**
     *
     * @var integer
     * @Column(type="integer", length=2, nullable=true)
     * 0=自动，1=手动
     */
    public $iSource;

    /**
     *
     * @var integer
     * @Column(type="integer", length=4, nullable=true)
     * 1=正常，2=校购
     */
    public $iBuyType;

    /**
     *
     * @var integer
     * @Column(type="integer", length=4, nullable=true)
     * 是否演示
     */
    public $bDemo;

    /**
     *
     * @var integer
     * @Column(type="integer", length=4, nullable=true)
     */
    public $bHistory;
    public $iCheck;
    public $sNewReceiver;
    public $iNewPurpose;
    public $sNewNowReceiver;
    public $iNewSchoolId;
    public $iBeforeUTId;
    public $iNewUTId;
    /**
     *
     * @var integer
     * @Column(type="integer", length=1, nullable=true)
     */
    public $bDelete;

    /**
     *
     * @var string
     * @Column(type="string", nullable=true)
     */
    public $tCreateDate;

    /**
     *
     * @var integer
     * @Column(type="integer", length=20, nullable=true)
     */
    public $iCreateUserId;

    /**
     *
     * @var string
     * @Column(type="string", nullable=true)
     */
    public $tLastModifyDate;

    /**
     *
     * @var integer
     * @Column(type="integer", length=20, nullable=true)
     */
    public $iLastModifyUserId;

    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        parent::initialize();
    }

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'XHSys_UserTablet';
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhsysUsertablet[]|XhsysUsertablet
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhsysUsertablet
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    public function beforeCreate()
    {
        if ($this->sNowReceiverAccount && !$this->iNowReceiverId) {
            $user = XhsysUser::findFirst([
                'columns'    => 'iUserId',
                'conditions' => 'bDelete = 0 AND sLogonName = :logonName:',
                'bind'       => ['logonName' => $this->sNowReceiverAccount]
            ]);
            if (!$user) {
                throw new \Exception('当前领用用户不存在');
            }
            $this->iNowReceiverId = $user->iUserId;
        }

        //处理history
        $history = self::find([
            'conditions' => 'bDelete = 0 and sDevNumber = :devNumber:',
            'bind'  => ['devNumber' => $this->sDevNumber]
        ]);
        foreach ($history as $obj) {
            $obj->bHistory = 1;
            if (!$obj->save()) {
                throw new \Exception($history->getError());
            }
        }
        $userId  = User::getId();
        $time    = date('Y-m-d H:i:s');
        //创建时未登录处理

        $this->iCreateUserId = $userId;
        $this->tLastModifyDate = $time;
        $this->iLastModifyUserId = User::getId();
        if (!$userId && $this->iReceivePurpose == 3 && $this->iSource == 0) {
            $user = XhsysUser::findFirst([
                'columns'    => 'iUserId',
                'conditions' => 'bDelete = 0 AND sLogonName = :logonName:',
                'bind'       => ['logonName' => $this->sReceiverAccount]
            ]);
            if ($user) {
                $appInfo = XHImsApplyTablet::findFirst([
                    'columns'   => 'iCreateUserId',
                    'conditions' => "bDelete = 0 and iSignState = 1 and CONCAT(',',sTeachers,',') like :key:",
                    'bind'       => ['key' => '%,'.$user->iUserId.',%']
                ]);
                if ($appInfo) {
                    $this->iCreateUserId = $appInfo->iCreateUserId;
                    $this->iLastModifyUserId = $appInfo->iCreateUserId;
                }
            }
        }
        return true;
//        return parent::beforeCreate();
    }



    public function beforeUpdate()
    {
        if ($this->hasChanged('sNowReceiverAccount') && $this->sNowReceiverAccount) {
            $user = XhsysUser::findFirst([
                'columns'    => 'iUserId',
                'conditions' => 'bDelete = 0 AND sLogonName = :logonName:',
                'bind'       => ['logonName' => $this->sNowReceiverAccount]
            ]);
            if (!$user) {
                throw new \Exception('当前领用用户不存在');
            }
            $this->iNowReceiverId = $user->iUserId;
        }
        if (!$this->sNowReceiverAccount) {
            $this->iNowReceiverId = 0;
        }
        return parent::beforeUpdate();
    }

    public function beforeSave()
    {
        $this->sDevNumber = trim($this->sDevNumber);
        return true;
    }

    /**
     * 根据id数组删除记录
     *
     * @param $idArr
     * @return bool
     *
     * create by ck 20170619
     */
    public static function deleteRecordById($idArr)
    {
        return self::find([
            'conditions' => 'iUTId in ({idArr:array})',
            'bind'       => ['idArr' => $idArr]
        ])->delete();
    }

}
